import 'dart:math';
import 'dart:ui';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CanvasScalePainter extends CustomPainter{
  late Paint _paint;
  double step = 20;//小格边长

  CanvasScalePainter(){
    _paint = Paint()
        ..style = PaintingStyle.stroke
        ..color = Colors.grey
        ..strokeWidth = .5;
  }

  final List<Offset> points = [
    Offset(-120, -120),
    Offset(-80, -180),
    Offset(-40, -140),
    Offset(0, -190),
    Offset(40, -140),
    Offset(80, -160),
    Offset(120, -100),
  ];

  @override
  void paint(Canvas canvas, Size size) {
    // TODO: implement paint
    canvas.translate(size.width/2 , size.height/2 );
    _drawGrid(canvas,size);//网格

    _drawPart(canvas);//蓝圆
    var paint = Paint();
    _drawDot(canvas,paint);

    _drawPointsWithPoints(canvas);
  }

  void _drawPointsWithPoints(Canvas canvas) {
    _paint
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth=10
      ..strokeCap = StrokeCap.round;
    canvas.drawPoints(PointMode.points, points, _paint);
  }

  void _drawDot(Canvas canvas, Paint paint) {
    final int count = 12;
    paint
      ..color = Colors.orangeAccent
      ..style = PaintingStyle.stroke
      ..strokeCap = StrokeCap.round
      ..strokeWidth = 5;
    canvas.save();
    for (int i = 0; i < count; i++) {
      var step =  2*pi/count ;
      canvas.drawLine(Offset(80, 0), Offset(100, 0), paint);
      canvas.rotate(step);
    }
    canvas.restore();
  }

  void _drawPart(Canvas canvas) {
    var paint = Paint()
      ..style = PaintingStyle.fill
      ..color = Colors.blue;
    canvas.drawCircle(Offset(0, 0), 50, paint);
    canvas.drawLine(
        Offset(20, 20),
        Offset(50, 50),
        paint
          ..color = Colors.red
          ..strokeWidth = 5
          ..strokeCap = StrokeCap.round
          ..style = PaintingStyle.stroke);
  }

  _drawGrid(Canvas canvas, Size size){
    _drawBottomRight(canvas,size);

    canvas.save();
    canvas.scale(1, -1); //沿x轴镜像
    _drawBottomRight(canvas, size);
    canvas.restore();

    canvas.save();
    canvas.scale(-1, 1); //沿y轴镜像
    _drawBottomRight(canvas, size);
    canvas.restore();

    canvas.save();
    canvas.scale(-1, -1); //沿原点镜像
    _drawBottomRight(canvas, size);
    canvas.restore();
  }

  //初步画网格线
  _drawBottomRight(Canvas canvas, Size size){
    canvas.save();
    for(int i = 0;i < size.height/2/step;i++){
      canvas.drawLine(Offset(0,0), Offset(size.width/2, 0), _paint);
      canvas.translate(0, step);
    }
    canvas.restore();

    canvas.save();
    for(int i = 0;i < size.width/2/step;i++){
      canvas.drawLine(Offset(0,0), Offset(0, size.height/2), _paint);
      canvas.translate(step, 0);
    }
    canvas.restore();
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // TODO: implement shouldRepaint
    return true;
  }

}